/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gos.creator.util;

import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @author Xue Liang
 */
public class VelocityEngineUtil {

    private static final VelocityEngine ENGINE = new VelocityEngine();

    static {
        ENGINE.addProperty(RuntimeConstants.ENCODING_DEFAULT, StandardCharsets.UTF_8.name());
        ENGINE.addProperty(RuntimeConstants.INPUT_ENCODING, StandardCharsets.UTF_8.name());
        ENGINE.addProperty(RuntimeConstants.OUTPUT_ENCODING, StandardCharsets.UTF_8.name());
        ENGINE.addProperty(RuntimeConstants.MAX_NUMBER_LOOPS, 2 << 10);
    }

    private VelocityEngineUtil() {

    }

    public static VelocityEngine getVelocityEngine() {
        return ENGINE;
    }

    public static Template getTemplate(File templateFile) {
        if (templateFile.exists() && templateFile.isFile()) {
            ENGINE.addProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateFile.getParent());
            Template template = ENGINE.getTemplate(templateFile.getName(), StandardCharsets.UTF_8.name());
            template.setEncoding(StandardCharsets.UTF_8.name());
            return template;
        }
        return null;
    }
}
